<?php
require_once 'includes/header.php';
require_once 'includes/DatabaseHelper.php';

require_once 'includes/functions.php';

$db = Database::getInstance();

// 处理用户删除请求
if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    $userId = (int)$_GET['delete'];
    
    // 检查是否为当前登录用户
    if ($userId == $auth->getUserId()) {
        $_SESSION['flash_message'] = '不能删除当前登录的用户';
        $_SESSION['flash_type'] = 'danger';
    } else {
        // 检查用户是否存在
        $user = $db->fetchRow("SELECT * FROM " . DB_PREFIX . "users WHERE id = ?", [$userId]);
        
        if ($user) {
            // 删除与用户相关的记录
            $db->execute("DELETE FROM " . DB_PREFIX . "user_achievements WHERE user_id = ?", [$userId]);
            $db->execute("DELETE FROM " . DB_PREFIX . "game_records WHERE user_id = ?", [$userId]);
            $db->execute("DELETE FROM " . DB_PREFIX . "users WHERE id = ?", [$userId]);
            
            $_SESSION['flash_message'] = '用户已成功删除';
            $_SESSION['flash_type'] = 'success';
        } else {
            $_SESSION['flash_message'] = '用户不存在';
            $_SESSION['flash_type'] = 'danger';
        }
    }
    
    // 重定向以防止重复提交
    header('Location: users.php');
    exit;
}

// 处理用户状态修改请求
if (isset($_GET['status']) && is_numeric($_GET['user_id'])) {
    $userId = (int)$_GET['user_id'];
    $status = $_GET['status'] === 'active' ? 'active' : 'inactive';
    
    // 检查是否为当前登录用户
    if ($userId == $auth->getUserId()) {
        $_SESSION['flash_message'] = '不能修改当前登录用户的状态';
        $_SESSION['flash_type'] = 'danger';
    } else {
        // 更新用户状态
        $db->update('users', ['status' => $status], 'id = ?', [$userId]);
        
        $_SESSION['flash_message'] = '用户状态已更新';
        $_SESSION['flash_type'] = 'success';
    }
    
    // 重定向以防止重复提交
    header('Location: users.php');
    exit;
}

// 分页设置
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$perPage = 10;
$offset = ($page - 1) * $perPage;

// 搜索功能
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$searchCondition = '';
$searchParams = [];

if (!empty($search)) {
    $searchCondition = " WHERE (username LIKE ? OR email LIKE ? OR nickname LIKE ?)";
    $searchParams = ["%$search%", "%$search%", "%$search%"];
}

// 获取用户总数
$totalUsers = $db->fetchColumn(
    "SELECT COUNT(*) FROM " . DB_PREFIX . "users" . $searchCondition, 
    $searchParams
);

// 获取用户列表
$users = $db->fetchAll(
    "SELECT * FROM " . DB_PREFIX . "users" . $searchCondition . " ORDER BY id DESC LIMIT ?, ?", 
    array_merge($searchParams, [$offset, $perPage])
);

// 计算总页数
$totalPages = ceil($totalUsers / $perPage);
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h1><i class="bi bi-people"></i> 用户管理</h1>
    <a href="user_edit.php" class="btn btn-primary">
        <i class="bi bi-person-plus"></i> 添加用户
    </a>
</div>

<!-- 搜索框 -->
<div class="card mb-4">
    <div class="card-body">
        <form action="users.php" method="get" class="row g-3">
            <div class="col-md-6">
                <div class="input-group">
                    <input type="text" class="form-control" id="search" name="search" 
                           placeholder="搜索用户名、邮箱或昵称" value="<?php echo htmlspecialchars($search); ?>">
                    <button class="btn btn-primary" type="submit">
                        <i class="bi bi-search"></i> 搜索
                    </button>
                </div>
            </div>
            <?php if (!empty($search)): ?>
                <div class="col-md-2">
                    <a href="users.php" class="btn btn-outline-secondary w-100">清除搜索</a>
                </div>
            <?php endif; ?>
        </form>
    </div>
</div>

<!-- 用户列表 -->
<div class="card mb-4">
    <div class="card-header">
        <i class="bi bi-table me-1"></i> 用户列表
        <span class="badge bg-info ms-2"><?php echo $totalUsers; ?> 个用户</span>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-bordered table-hover">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>用户名</th>
                        <th>邮箱</th>
                        <th>注册时间</th>
                        <th>状态</th>
                        <th>角色</th>
                        <th>最后登录</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (!empty($users)): ?>
                        <?php foreach ($users as $user): ?>
                        <tr>
                            <td><?php echo $user['id']; ?></td>
                            <td>
                                <?php if (!empty($user['avatar'])): ?>
                                    <img src="<?php echo htmlspecialchars($user['avatar']); ?>" alt="头像" class="avatar-sm rounded-circle me-1">
                                <?php else: ?>
                                    <i class="bi bi-person-circle me-1"></i>
                                <?php endif; ?>
                                <?php echo htmlspecialchars($user['username']); ?>
                            </td>
                            <td><?php echo htmlspecialchars($user['email']); ?></td>
                            <td><?php echo date('Y-m-d H:i', strtotime($user['created_at'])); ?></td>
                            <td>
                                <?php if ($user['status'] == 'active'): ?>
                                    <span class="badge bg-success">活跃</span>
                                <?php else: ?>
                                    <span class="badge bg-secondary">禁用</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php if ($user['role'] == 'admin'): ?>
                                    <span class="badge bg-danger">管理员</span>
                                <?php else: ?>
                                    <span class="badge bg-info">普通用户</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php echo !empty($user['last_login']) ? date('Y-m-d H:i', strtotime($user['last_login'])) : '未登录'; ?>
                            </td>
                            <td>
                                <div class="btn-group btn-group-sm">
                                    <a href="user_detail.php?id=<?php echo $user['id']; ?>" class="btn btn-info">
                                        <i class="bi bi-eye"></i>
                                    </a>
                                    <a href="user_edit.php?id=<?php echo $user['id']; ?>" class="btn btn-primary">
                                        <i class="bi bi-pencil"></i>
                                    </a>
                                    <?php if ($user['id'] != $auth->getUserId()): ?>
                                        <?php if ($user['status'] == 'active'): ?>
                                            <a href="users.php?user_id=<?php echo $user['id']; ?>&status=inactive" 
                                               class="btn btn-warning" 
                                               onclick="return confirm('确定要禁用此用户吗？')">
                                                <i class="bi bi-slash-circle"></i>
                                            </a>
                                        <?php else: ?>
                                            <a href="users.php?user_id=<?php echo $user['id']; ?>&status=active" 
                                               class="btn btn-success">
                                                <i class="bi bi-check-circle"></i>
                                            </a>
                                        <?php endif; ?>
                                        <a href="users.php?delete=<?php echo $user['id']; ?>" 
                                           class="btn btn-danger" 
                                           onclick="return confirm('确定要删除此用户吗？此操作不可撤销，用户的所有数据将被删除。')">
                                            <i class="bi bi-trash"></i>
                                        </a>
                                    <?php endif; ?>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="8" class="text-center">没有找到符合条件的用户</td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
    
    <!-- 分页 -->
    <?php if ($totalPages > 1): ?>
    <div class="card-footer">
        <nav>
            <ul class="pagination justify-content-center mb-0">
                <?php
                // 分页导航
                renderPagination($page, $totalPages, 'users.php', ['search' => $search]);
                ?>
            </ul>
        </nav>
    </div>
    <?php endif; ?>
</div>

<?php
require_once 'includes/footer.php';
?> 